package com.wangziyu.facerecognitiongate.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.wangziyu.facerecognitiongate.bean.TreeNode
import com.wangziyu.facerecognitiongate.databinding.ItemTreeNodeBinding

/**
 * @description 树结构适配器
 * @author wzy
 * @date 2025/08/18 22:48:48
 */
class TreeAdapter(
    private val rootNodes: List<TreeNode>
) : RecyclerView.Adapter<TreeAdapter.TreeViewHolder>() {

    // 当前可见节点列表
    private val visibleNodes = mutableListOf<TreeNode>()

    init {
        buildVisibleList()
    }

    private fun buildVisibleList() {
        visibleNodes.clear()
        rootNodes.forEach { addNodeRecursively(it) }
    }

    private fun addNodeRecursively(node: TreeNode) {
        visibleNodes.add(node)
        if (node.isExpanded) {
            node.children.forEach { addNodeRecursively(it) }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TreeViewHolder {
        val binding = ItemTreeNodeBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return TreeViewHolder(binding)
    }

    override fun onBindViewHolder(holder: TreeViewHolder, position: Int) {
        val node = visibleNodes[position]
        holder.bind(node)
        holder.binding.tvExpand.setPadding(node.level * 100, 0, 0, 0) // 缩进

        holder.binding.root.setOnClickListener {
            if (node.children.isNotEmpty()) {
                node.isExpanded = !node.isExpanded
                buildVisibleList()
                notifyDataSetChanged()
            }
        }
    }

    override fun getItemCount(): Int = visibleNodes.size

    fun getVisibleNodes(): List<TreeNode> = visibleNodes

    class TreeViewHolder(val binding: ItemTreeNodeBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(node: TreeNode) {
            binding.node = node
            binding.executePendingBindings()
        }
    }
}